package cn.lastcc.pwdmanage.core;

import android.content.Context;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import cn.lastcc.pwdmanage.entity.IConstant;
import cn.lastcc.pwdmanage.entity.Info;

import static cn.lastcc.pwdmanage.entity.IConstant.TAG;

/**
 * 序列化相关工具，主要用于存取数据文件，作为本程序的持久化工具
 *
 * @author Added by baidongyang 2013-6-23
 *
 */
public class SerialUtil {

    private static SerialUtil sInstance = null;
    private Context mContext = null;
    private Info mInfo = null;

    public static SerialUtil getInstance(Context context) {
        if (null == sInstance) {
            sInstance = new SerialUtil(context);
        }
        return sInstance;
    }

    private SerialUtil(Context context) {
        mContext = context;
    }

    public Info getInfo() throws IOException, ClassNotFoundException {
        if (null == mInfo) {
            // 进行反序列化
            ObjectInputStream in = null;
            Object obj = null;
            try {
                in = new ObjectInputStream(mContext.openFileInput(IConstant.INFO_FILE_NAME));
                obj = in.readObject();
            } catch (IOException e) {
                throw e;
            } finally {
                if (null != in) {
                    in.close();
                }
            }
            if (obj instanceof Info) {
                mInfo = (Info) obj;
            } else {
                throw new InvalidObjectException("文件解析失败");
            }
        }
        return mInfo;
    }

    public void setInfo(Info info) throws IOException {
        mInfo = info;
        if (null == info) {
            Log.w(TAG, "Info object is null, nothing to be done.");
            return ;
        }
        // 序列化文件保存数据
        ObjectOutputStream out = null;
        try {
            out = new ObjectOutputStream(mContext.openFileOutput(IConstant.INFO_FILE_NAME, Context.MODE_PRIVATE));
            out.writeObject(info);
            out.flush();
        } finally {
            if (null != out) {
                out.close();
            }
        }
    }
}
